<template>
  <el-dialog
    width="30%"
    :title="title"
    :visible.sync="dialogFormVisible"
    @close="close"
  >
    <div>
      <tree
        :nodes="nodes"
        class="tree max-300"
        ref="treeAuth"
        @onClick="selectTree"
        :setting="setting"
        @onCreated="handleCreated"
      />
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button @loading="loading" type="primary" @click="save">
        确 定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { changeGroup } from '@/api/userManagement'
  import { getGrouplist } from '@/api/ad'
  import tree from 'vue-giant-tree'
  export default {
    components: { tree },
    data() {
      return {
        loading: false,
        nodes: [],
        ztreeObj: null,
        grouplist: [],
        setting: {
          data: {
            simpleData: {
              enable: true,
              pIdKey: 'pid',
            },
          },
          view: {
            showIcon: false,
            addHoverDom: this.addHoverDom,
            removeHoverDom: this.removeHoverDom,
          },
        },
        form: {
          id: '',
          group_d: '',
        },
        title: '',
        dialogFormVisible: false,
      }
    },
    created() {},
    methods: {
      getGroupListData() {
        getGrouplist({})
          .then((res) => {
            this.nodes = res.data.map((item, index) => {
              let datac = {}
              datac.id = item.id
              datac.pid = 0
              datac.name = item.gname
              return datac
            })
            this.grouplist = res.data
          })
          .catch((ret) => {
            console.log(ret)
          })
      },
      selectTree() {
        let node = this.ztreeObj.getSelectedNodes()[0]
        this.form.group_id = node.id
      },
      handleCreated: function (ztreeObj) {
        this.ztreeObj = ztreeObj
        if (this.ztreeObj.getNodes().length > 0) {
          const zobj = this.ztreeObj
            .getNodes()
            .find((item) => item.id == this.form.group_id)
          this.ztreeObj.selectNode(zobj, true)
        }
      },
      showEdit(row) {
        this.title = '移动到'
        this.getGroupListData()
        this.form = Object.assign(this.form, row)
        this.dialogFormVisible = true
      },
      close() {
        this.form = this.$options.data().form
        this.dialogFormVisible = false
      },
      async save() {
        this.loading = true
        const res = await changeGroup({
          groupid: String(this.form.group_id),
          uid: this.form.uid,
        })
        this.$baseMessage('操作成功!', 'success')
        this.loading = false
        this.close()
        this.$emit('fetch-data')
      },
    },
  }
</script>
<style lang="scss" scoped>
  .max-300 {
    max-height: 300px;
    overflow-y: auto;
  }
</style>
